677. 键值映射
https://leetcode-cn.com/problems/map-sum-pairs/
- 提交时间:2021-11-13 18:37:50
- 执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
- 内存消耗:2.7 MB, 在所有 Go 提交中击败了64.41%的用户
- 通过测试用例:35 / 35
type MapSum struct {
stage map[string]int
pre map[string]int
}
func Constructor() MapSum {
return MapSum{stage: make(map[string]int), pre: make(map[string]int)}
}
func (m *MapSum) Insert(key string, val int) {
if oldVal, ok := m.stage[key]; ok {
if oldVal == val {
return
}
for i := 1; i <= len(key); i++ {
m.pre[key[0:i]] += (val - oldVal)
}
m.stage[key] = val
return
}
for i := 1; i <= len(key); i++ {
m.pre[key[0:i]] += val
}
m.stage[key] = val
}
func (m *MapSum) Sum(prefix string) int {
return m.pre[prefix]
}
/**
* Your MapSum object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(key,val);
* param_2 := obj.Sum(prefix);
*/